package com.teamwork.shareplatform.controller;

import com.github.pagehelper.PageInfo;
import com.teamwork.shareplatform.entity.Files;
import com.teamwork.shareplatform.service.FilesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api")
public class FilesController {

    private static final Logger logger = LoggerFactory.getLogger(FilesController.class);

    @Autowired
    FilesService filesService;

    @Value("${file.upload.path}")
    private String uploadPath;

    // 获取用户上传列表
    @GetMapping("/user/myfile")
    public ResponseEntity<CommonResult<PageInfo>> getUserFileList(@RequestParam("id") int id,
                                                                  @RequestParam(value = "currentPage", defaultValue = "1") int currentPage,
                                                                  @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        return getFileListResponse(filesService.queryByUid(id, currentPage, pageSize), "获取成功");
    }

    // 获取全部文件列表
    @GetMapping("/admin/files")
    public ResponseEntity<CommonResult<PageInfo>> getAllFiles(@RequestParam(value = "currentPage", defaultValue = "1") int currentPage,
                                                              @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        return getFileListResponse(filesService.queryAllFiles(currentPage, pageSize), "获取成功");
    }

    // 获取单科文件列表
    @GetMapping("/user/subjectfiles")
    public ResponseEntity<CommonResult<PageInfo>> getSubjectsFiles(@RequestParam("sid") int sid,
                                                                   @RequestParam(value = "currentPage", defaultValue = "1") int currentPage,
                                                                   @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        return getFileListResponse(filesService.queryByCid(sid, currentPage, pageSize), "获取成功");
    }

    private ResponseEntity<CommonResult<PageInfo>> getFileListResponse(List<Files> files, String message) {
        PageInfo pageInfo = new PageInfo<>(files);
        CommonResult<PageInfo> commonResult = new CommonResult<>();
        commonResult.setCode(200);
        commonResult.setMessage(message);
        commonResult.setData(pageInfo);
        return ResponseEntity.ok(commonResult);
    }

    // 删除一个文件
    @GetMapping("/admin/delFile")
    public ResponseEntity<CommonResult<Integer>> delOneFile(@RequestParam int id) {
        try {
            String filePath = filesService.queryFilePath(id);
            int flag = filesService.deleteFiles(id);
            CommonResult<Integer> commonResult = new CommonResult<>();
            if (flag > 0) {
                File file = new File(filePath);
                if (file.exists() && file.delete()) {
                    commonResult.setCode(200);
                    commonResult.setMessage("删除成功");
                } else {
                    commonResult.setCode(-1);
                    commonResult.setMessage("文件删除失败，但数据库记录已删除");
                }
            } else {
                commonResult.setCode(-1);
                commonResult.setMessage("删除失败");
            }
            return ResponseEntity.ok(commonResult);
        } catch (Exception e) {
            logger.error("删除文件时发生异常", e);
            CommonResult<Integer> errorResult = new CommonResult<>();
            errorResult.setCode(-1);
            errorResult.setMessage("删除文件时发生异常：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
        }
    }

    // 上传文件
    @PostMapping("/user/upload")
    public ResponseEntity<CommonResult<Integer>> uploadFile(@RequestParam int sid,
                                                            @RequestParam int uid,
                                                            @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            CommonResult<Integer> result = new CommonResult<>();
            result.setCode(-1);
            result.setMessage("文件不能为空");
            return ResponseEntity.badRequest().body(result);
        }
        try {
            String dname = file.getOriginalFilename();
            float fl = (float) file.getSize() / 1024;
            String dsize = new BigDecimal(fl).setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "KB";
            File targetFile = new File(uploadPath, dname);
            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            file.transferTo(targetFile);

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String ctime = df.format(new Date());

            Files files = new Files();
            files.setCtime(ctime);
            files.setDname(dname);
            files.setPath(targetFile.getAbsolutePath());
            files.setSid(sid);
            files.setUid(uid);
            files.setDsize(dsize);

            int fid = filesService.addFiles(files);
            CommonResult<Integer> result = new CommonResult<>();
            if (fid > 0) {
                result.setCode(200);
                result.setMessage("上传成功");
                result.setData(fid);
            } else {
                result.setCode(-1);
                result.setMessage("上传失败");
            }
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            logger.error("上传文件时发生异常", e);
            CommonResult<Integer> errorResult = new CommonResult<>();
            errorResult.setCode(-1);
            errorResult.setMessage("上传文件时发生异常：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
        }
    }

    // 文件下载
    @GetMapping("/user/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam String dname) {
        File file = new File(uploadPath, dname);
        if (!file.exists()) {
            return ResponseEntity.notFound().build();
        }
        Resource resource = new FileSystemResource(file);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode(dname, StandardCharsets.UTF_8));
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .body(resource);
    }
}
